from django.shortcuts import render
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.db.models import Q
# Create your views here.
from .. import models
from .viewsIndex import uploads
from .viewsIndex import pages
import os
from web.settings import BASE_DIR
from django.contrib.auth.decorators import permission_required


@permission_required('myadmin.show_goods',raise_exception = True)
#商品列表
def goodsindex(request):
    # 查询
    data = models.Goods.objects.filter().exclude(status=2)

    # 获取请求参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否右搜索条件
    if types:
        if types == 'title':
            # 按标题搜索
            data = data.filter(title__contains=keywords)
        elif types == 'price':
      
            # 获取价格区间
            arr = keywords.split(',')
            data = data.filter(price__gte=arr[0]).filter(price__lte=arr[1])

        elif types == 'status':
            # 按状态搜索
            pass

    #分页函数调用       
    goodslist = pages(data,request)
    #分配数据
    context = {'goodslist':goodslist}
    # 加载模板
    return render(request,'myadmin/goods/index.html',context)


@permission_required('myadmin.insert_goods',raise_exception = True)
# 商品添加 
def goodsadd(request):
    # 获取所有的商品分类
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths').exclude(isDelete=1)
    # 分配数据
    context = {'cateslist':data}
    # 加载模板
    return render(request,'myadmin/goods/add.html',context)


@permission_required('myadmin.insert_goods',raise_exception = True)
# 执行商品添加 
def goodsinsert(request):
    try:
        # 接受数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        # cateid是外键 添加的时候得是对象
        data['cateid'] = models.Cates.objects.get(id=data['cateid'])

        # 处理上传的商品主图
        myfile = request.FILES.get('pic_url')
        if myfile:
            data['pic_url'] = uploads(myfile)
        else:
            return HttpResponse('<script>alert("必须上传商品主图");history.back(-1);</script>')#history.back(-1)回到上一步

        # 执行数据的添加
        ob = models.Goods(**data)
        ob.save()
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_goods_add')+'"</script>')


@permission_required('myadmin.del_goods',raise_exception = True)
#商品下架 逻辑下架
def goodsdel(request,gid):
    try:
        #根据uid获取用户对象,修改状态
        ob = models.Goods.objects.get(id=gid)
        ob.status = 2
        ob.save()
        return HttpResponse('<script>alert("下架成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("下架失败");location.href="'+reverse('myadmin_goods_index')+'"</script>')

@permission_required('myadmin.del_goods',raise_exception = True)    
#下架商品列表
def goodsdeletelist(request):
    #获取所有用户数据
    data = models.Goods.objects.filter(status=2)

    # 获取请求参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否右搜索条件
    if types:
        if types == 'title':
            # 按标题搜索
            data = data.filter(title__contains=keywords)
        elif types == 'price':
      
            # 获取价格区间
            arr = keywords.split(',')
            data = data.filter(price__gte=arr[0]).filter(price__lte=arr[1])

        elif types == 'status':
            # 按状态搜索
            pass

    #分页函数调用       
    goodslist = pages(data,request)
    #分配数据
    context = {'goodslist':goodslist}
    return render(request,'myadmin/goods/deletelist.html',context)   


#后台商品还原
def goodsopen(request,gid):
    # try:
        # 判断当前类下是否还有父类
        num = models.Goods.objects.get(id=gid).cateid.isDelete
        if num == 0 :
            #根据uid获取用户对象,修改状态
            ob = models.Goods.objects.get(id=gid)
            ob.status = 0
            ob.save()
            return HttpResponse('<script>alert("还原成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
        else:
            return HttpResponse('<script>alert("还原失败,请先还原上一级");location.href="'+reverse('myadmin_goods_deletelist')+'"</script>')    
    # except:
    #     return HttpResponse('<script>alert("还原失败");location.href="'+reverse('myadmin_goods_index')+'"</script>') 

@permission_required('myadmin.del_goods',raise_exception = True)
#商品删除 逻辑删除
def goodsdelete(request,gid):
    try:
        #根据uid获取用户对象,修改状态
        ob = models.Goods.objects.get(id=gid)
        ob.delete()
        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_goods_deletelist')+'"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_goods_deletelist')+'"</script>')


@permission_required('myadmin.edit_goods',raise_exception = True)
#显示编辑表单,执行编辑
def goodsedit(request,gid):
    #根据uid获取商品对象
    ob =models.Goods.objects.get(id=gid)
    # 获取所有的商品分类
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths').exclude(isDelete=1)
    #判断请求方式
    if request.method == 'GET':
        #显示编辑表单
        return render(request,'myadmin/goods/edit.html',{'ginfo':ob,'cateslist':data})
    elif request.method == 'POST':
        try:
            #执行编辑
            ob.title = request.POST.get('title')
            ob.price = request.POST.get('price')
            ob.store = request.POST.get('store')
            ob.clicknum = request.POST.get('clicknum')
            ob.ordernum = request.POST.get('ordernum')
            ob.cateid = models.Cates.objects.get(id=request.POST.get('cateid'))
            # ob.info = request.POST.get('info')
            # 判断是否更新了主图
            myfile = request.FILES.get('pic_url')
            if myfile:
                try:
                    # 如果修改了主图,要上传新的主图
                    # 删除原来上传的主图
                    os.remove(BASE_DIR+ob.pic_url)
                except:
                        pass
                # 更新主图
                ob.pic_url = uploads(myfile)
            # 执行数据的更新
            ob.save()
            return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
        except:
            return HttpResponse('<script>alert("更新失败");history.back(-1);"</script>')